//
//  DialPhoneViewController.m
//  ChengXinBao
//
//  Created by RongZhou on 17/2/13.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "DialPhoneViewController.h"
#import "LLKCollectionManage.h"
#import "CallModel.h"
#import "DialRecordCell.h"
#import "PPGetAddressBook.h"
#import "DialDetailInformationViewController.h"
#import <AFNetworking.h>
typedef NSString* (^codeAreaBlock)(NSString *);
@interface DialPhoneViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *addressArray;
@property(nonatomic,strong)NSMutableArray *countArray;
@property(nonatomic,copy)NSString *addressName;
@property(nonatomic,strong)NSMutableArray *souSuoArray;
@property(nonatomic,assign)BOOL goSearch;
@property(nonatomic,copy)NSString *searchNumber;
@property(nonatomic,copy)NSString *codeArea;
@property(nonatomic,copy)codeAreaBlock areablock;
@end

@implementation DialPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"通话记录";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNumberlabelText:) name:@"labelText" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadNewData) name:@"backAndReloadData" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadNewData) name:@"closeKeyboard" object:nil];
}
-(void)reloadNewData{
    [self.addressArray removeAllObjects];
    [self.countArray removeAllObjects];
    self.goSearch = NO;
    [self initUIAboutTableview];
}
-(void)checkNumberlabelText:(NSNotification *)noti{
    
    NSString *labelText = noti.userInfo[@"labelText"];
    self.searchNumber = noti.userInfo[@"labelText"];
    NSLog(@"想要看我吗%@",noti.userInfo[@"labelText"]);
    if ([labelText isEqual:@""]) {
        self.goSearch = NO;
        [self initUIAboutTableview];
    }else{
        self.goSearch = YES;
        [self.addressArray removeAllObjects];
        [self.countArray removeAllObjects];
        [self.souSuoArray removeAllObjects];
        [self getSousuoDataAboutData:labelText];
    }
}
#pragma mark -检测拨号键盘的搜索功能

-(void)getSousuoDataAboutData:(NSString *)phoneStr{
    [PPGetAddressBook getOriginalAddressBook:^(NSArray<PPPersonModel *> *addressBookArray) {
        for (PPPersonModel *model in addressBookArray) {
            for (NSString *str in model.mobileArray) {
                if ([str rangeOfString:phoneStr].length >0) {
                    [self.souSuoArray addObject:model];
                }
            }
        }
        NSLog(@"我是当前线程%@",[NSThread currentThread]);
        [self.tableView reloadData];
    } authorizationFailure:^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"提示" message:@"请在iPhone的“设置-隐私-通讯录”选项中，允许诚信宝访问您的通讯录" delegate: nil cancelButtonTitle: @"知道了" otherButtonTitles: nil];
        [alert show];
    }];
}
#pragma mark
-(void)viewWillAppear:(BOOL)animated{
    self.goSearch = NO;
  [self initUIAboutTableview];
}
-(void)viewWillDisappear:(BOOL)animated{

}
-(void)viewDidDisappear:(BOOL)animated{
    [self.addressArray removeAllObjects];
    [self.countArray removeAllObjects];
}
-(void)createUIAboutSearchBar{
    
}
-(void)initUIAboutTableview{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectZero];
    footerView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = footerView;
    UINib *nib = [UINib nibWithNibName:@"DialRecordCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"DialRecordCell"];    dispatch_queue_t gloablQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(gloablQueue, ^{
        NSMutableArray *array = [[LLKCollectionManage shareManager] selectAll];
        for (NSInteger i = array.count - 1  ; i >= 0; i--) {
            [self.addressArray addObject:array[i]];
        }
        NSLog(@"%@",self.addressArray);
        for (NSInteger i = 0; i < self.addressArray.count ; i++) {
            NSInteger count = 1;
            CallModel *model1 = self.addressArray[i];
            for (NSInteger j = i + 1; j < self.addressArray.count; j++) {
                CallModel *model2 = self.addressArray[j];
                if ([model1.userPhonenumber isEqual:model2.userPhonenumber]) {
                    count++;
                    [self.addressArray removeObjectAtIndex:j];
                    j -= 1;
                    NSLog(@"%lu",(unsigned long)self.addressArray.count);
                }
            }
            [self.countArray addObject:[NSString stringWithFormat:@"%ld",(long)count]];
        }
        NSLog(@"2=%@",self.countArray);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}

#pragma mark -tableview的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.goSearch) {
        return self.souSuoArray.count;
    }
    return self.countArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.goSearch) {
        static NSString *cellId = @"cellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
            
        }

        PPPersonModel *model = self.souSuoArray[indexPath.row];
        cell.textLabel.text = model.name;
        if (model.mobileArray.count == 1) {
            cell.detailTextLabel.text = model.mobileArray[0];
        }else{
            for (NSString *str in model.mobileArray) {
                if ([str rangeOfString:self.searchNumber].length > 0) {
                    cell.detailTextLabel.text = str;
                }
            }
        }
        return cell;
    }else{
    DialRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DialRecordCell"];
    CallModel *model = self.addressArray[indexPath.row];
    NSString *count = self.countArray[indexPath.row];
    if ([count integerValue] == 1) {
        cell.userNameLabel.text = [NSString stringWithFormat:@"%@",model.userName];
    }else{
        cell.userNameLabel.text = [NSString stringWithFormat:@"%@(%@)",model.userName,count];
    }
    if ([model.userName isEqual:model.userPhonenumber]) {
        cell.userPhoneAndAdressLabel.text = model.userAddress;
    }else{
        cell.userPhoneAndAdressLabel.text = [NSString stringWithFormat:@"%@  %@",model.userPhonenumber,model.userAddress];
    }
    cell.dateLabel.text = [self formateDate:model.userCallTime];
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    if (self.goSearch) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *MessageStr = [NSString stringWithFormat:@"%@%@",@"tel://",cell.detailTextLabel.text];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:MessageStr]];
        [self justCheckPhoneNumberArea:cell.detailTextLabel.text Andtableviewcell:cell];
        
    }else{
    DialDetailInformationViewController *vc = [[DialDetailInformationViewController alloc] init];
    CallModel *model = self.addressArray[indexPath.row];
    vc.phoneNumber = model.userPhonenumber;
    vc.userName = model.userName;
    vc.phoneNumberArea = model.userAddress;
        
    [[NSNotificationCenter defaultCenter] postNotificationName:@"shouldcloseTheBorad" object:self];
    [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    CallModel *model = self.addressArray[indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //1.删除数据库中对应的数据
        [[LLKCollectionManage shareManager] deleteByuserPhonenumebr:model.userPhonenumber];
        //2.删除self.dataArray中对应的数据
        [self.addressArray removeObjectAtIndex:indexPath.row];
        [self.countArray removeObjectAtIndex:indexPath.row];
        //3.刷表
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSMutableArray *)addressArray{
    if (_addressArray == nil) {
        _addressArray = [[NSMutableArray alloc] init];
    }
    return _addressArray;
}
-(NSMutableArray *)countArray{
    if (_countArray == nil) {
        _countArray = [[NSMutableArray alloc] init];
    }
    return _countArray;
}
-(NSMutableArray *)souSuoArray{
    if (_souSuoArray == nil) {
        _souSuoArray = [[NSMutableArray alloc] init];
    }
    return _souSuoArray;
}
/**
 *  计算当前时间与拨号时间的时间差
 *
 *  @param dateString <#dateString description#>
 *
 *  @return <#return value description#>
 */
- (NSString *)formateDate:(NSString *)dateString
{
    
    // ------实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY年-MM月-dd日 HH:mm"];//这里的格式必须和DateString格式一致
    
    NSDate * nowDate = [NSDate date];
    
    // ------将需要转换的时间转换成 NSDate 对象
    NSDate * needFormatDate = [dateFormatter dateFromString:dateString];
    
    // ------取当前时间和转换时间两个日期对象的时间间隔
    NSTimeInterval time = [nowDate timeIntervalSinceDate:needFormatDate];
    
    NSLog(@"time----%f",time);
    // ------再然后，把间隔的秒数折算成天数和小时数：
    
    NSString *dateStr = [[NSString alloc] init];
    
    if (time<=60) {  //1分钟以内的
        
        dateStr = @"刚刚";
        
    }else if(time<=60*60){  //一个小时以内的
        
        int mins = time/60;
        dateStr = [NSString stringWithFormat:@"%d分钟前",mins];
        
    }else if(time<=60*60*24){  //在两天内的
        
        [dateFormatter setDateFormat:@"YYYY-MM-dd"];
        NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
        NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
        
        [dateFormatter setDateFormat:@"HH:mm"];
        if ([need_yMd isEqualToString:now_yMd]) {
            //在同一天
            dateStr = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:needFormatDate]];
        }else{
            //昨天
            //                dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
            dateStr = [NSString stringWithFormat:@"%@",@"昨天"];
        }
    }else {
        
        [dateFormatter setDateFormat:@"yyyy"];
        NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
        NSString *nowYear = [dateFormatter stringFromDate:nowDate];
        
        if ([yearStr isEqualToString:nowYear]) {
            //在同一年
            [dateFormatter setDateFormat:@"MM-dd"];
            dateStr = [dateFormatter stringFromDate:needFormatDate];
        }else{
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            dateStr = [dateFormatter stringFromDate:needFormatDate];
        }
    }
    
    return dateStr;
}
/**
 *  获取手机号信息
 *
 *  @param phoneNumber <#phoneNumber description#>
 */
-(void)checkPhoneNumberArea:(NSString *)phoneNumber And:(PPPersonModel *)people{
    DialDetailInformationViewController *vc = [[DialDetailInformationViewController alloc] init];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = ServiceUrl@"/phoneAreaApp/searchCustomerByPhone?phone=%@";
    NSString *url = [NSString stringWithFormat:str,phoneNumber];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (dict[@"area"] == nil) {
            vc.phoneNumberArea = @"";
        }else{
            vc.phoneNumberArea = dict[@"area"];
        }
        vc.phoneNumber = phoneNumber;
        vc.userName = people.name;
        [self.navigationController pushViewController:vc animated:YES];
        NSLog(@"我是当前线程%@",[NSThread currentThread]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
/**
 *  计算当前拨号时间
 *
 *  @return 拨号时间
 */
-(NSString *)calueLocalDialPhoneNumberTime{
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    NSDate *date = [NSDate date];
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"YYYY年-MM月-dd日 HH:mm";
    [df setTimeZone:sourceTimeZone];//直接指定时区，北京时间
    return [df stringFromDate:date];
}
/**
 *  仅仅获取手机号信息
 *
 *  @param phoneNumber <#phoneNumber description#>
 */
-(void)justCheckPhoneNumberArea:(NSString *)phoneNumber Andtableviewcell:(UITableViewCell *)cell {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = ServiceUrl@"/phoneAreaApp/searchCustomerByPhone?phone=%@";
    NSString *url = [NSString stringWithFormat:str,phoneNumber];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (dict[@"area"] == nil) {
            self.codeArea = @"";
        }else{
            self.codeArea = dict[@"area"];
        }
        CallModel *modell = [[CallModel alloc] initWithUserName:cell.textLabel.text AndUserPhonenumber:cell.detailTextLabel.text AndUserCallTime:[self calueLocalDialPhoneNumberTime] AndUserAddress:self.codeArea];
        NSLog(@"%@",self.codeArea);
        [[LLKCollectionManage shareManager] addCollect:modell];
        self.goSearch = NO;
        [self.addressArray removeAllObjects];
        [self.countArray removeAllObjects];
        [self initUIAboutTableview];
        NSLog(@"我是当前线程%@",[NSThread currentThread]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

@end
